package controller

import (
	"fmt"
	"log"
	"strings"
	"sync"

	"user-agent/database/bean"
	"user-agent/database/myredis"

	"github.com/huyinghuan/moment"
	"github.com/kataras/iris/context"
)

type dbCtrl struct{}

var (
	aliveBean      = &bean.AliveBean{}
	statisticsBean = &bean.StatisticsBean{}
	DB             = &dbCtrl{}
)

func syncByTime(syncTime int64) string {
	keys := []string{}
	if err := myredis.SMembers("vps", &keys); err != nil {
		return err.Error()
	}
	var wg sync.WaitGroup
	fail := []string{}
	wg.Add(len(keys))
	for _, id := range keys {
		log.Println(id)
		go func(id string) {
			defer wg.Done()
			if count, err := statisticsBean.InertOrUpdate(id, syncTime); err != nil {
				log.Println(err)
				fail = append(fail, id)
			} else {
				myredis.HMSet("vps:"+id, "count", count)
			}
		}(id)
	}
	wg.Wait()
	if len(fail) == 0 {
		return fmt.Sprintf("同步成功: %s", moment.NewFromUnix(syncTime).Format("YYYY-MM-DD"))
	}
	return fmt.Sprintf("同步成功: %s \n 失败:\n%s", moment.NewFromUnix(syncTime).Format("YYYY-MM-DD"), strings.Join(fail, ","))
}

//Sync 同步某日数据
func (ctrl *dbCtrl) Sync(ctx context.Context) {
	syncTime := ctx.URLParamInt64Default("time", moment.Now().Unix())
	if syncTime == 0 {
		syncTime = moment.Now().Unix()
	}else if syncTime < 0{
	  syncTime = moment.Now().LastDay(-1 * int(syncTime)).Unix()
  }
	ctx.WriteString(syncByTime(syncTime))
}
